package com.barradata.common.rxbinding.click

import android.view.View
import androidx.annotation.MainThread
import io.reactivex.ObservableEmitter
import io.reactivex.ObservableOnSubscribe
import io.reactivex.android.MainThreadDisposable

/**
 * Created by WuNan-QF on 16/3/8.
 */
class ViewClickOnSubscribe<T :View> (internal val view: T) : ObservableOnSubscribe<T> {

    @MainThread
    @Throws(Exception::class)
    override fun subscribe(emitter: ObservableEmitter<T>) {
        view.setOnClickListener {
            if (!emitter.isDisposed) {
                @Suppress("UNCHECKED_CAST")
                emitter.onNext(it as T)
            }
        }

        emitter.setDisposable(object : MainThreadDisposable() {
            override fun onDispose() {
                view.setOnClickListener(null)
            }
        })
    }
}